package com.yugao.fintech.antelope.base.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtils {

    public static <T> void exportExcel(HttpServletResponse response,
                                       ExcelContentType excelContentType,
                                       ExportParams exportParams,
                                       String fileName,
                                       Class<T> pojoClass, List<T> data) throws Exception {
        response.reset();
        try (Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, data);
             ServletOutputStream outputStream = response.getOutputStream()) {
            response.flushBuffer();
            response.setContentType(excelContentType.getContentType());
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(outputStream);
        }
    }

    public static <T> void exportExcel(HttpServletResponse response,
                                       ExcelContentType excelContentType,
                                       String fileName,
                                       Class<T> pojoClass, List<T> data) throws Exception {
        response.reset();
        try (Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, data);
             ServletOutputStream outputStream = response.getOutputStream()) {
            response.flushBuffer();
            response.setContentType(excelContentType.getContentType());
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(outputStream);
        }
    }

    public static <T> List<T> importExcel(InputStream inputStream, Class<T> pojoClass) throws Exception {
        return ExcelImportUtil.importExcel(inputStream, pojoClass, new ImportParams());
    }

    public static <T> List<T> importExcel(InputStream inputStream, Class<T> pojoClass, ImportParams importParams) throws Exception {
        return ExcelImportUtil.importExcel(inputStream, pojoClass, importParams);
    }
}
